<template>
    
    <div>
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="100px" class="demo-ruleForm">
        <div class="container">
            <h3>基础信息</h3>
                <el-row style="margin-top:20px;">
                    <el-col :span="12">
                        <el-form-item label="产品标题：" >
                            <el-input placeholder="请输入内容" v-model.trim="ruleForm.title" style="width:300px">
                            </el-input>
                        </el-form-item>
                       <el-form-item label="电商链接：">
                        <el-input placeholder="不支持淘宝链接" v-model.trim="ruleForm.link" style="width:300px">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="价格：">
                            <el-input placeholder="请输入内容" v-model.trim="ruleForm.price" style="width:300px">
                            </el-input> <span style="margin-left:10px;">元</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                
            
        </div>
        <div class="container" style="margin-top:20px;">
            <h3>产品信息</h3>
            <!-- <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="100px" class="demo-ruleForm"> -->
                <el-row style="margin-top:20px;">
                    <el-col :span="22">
                        <el-form-item label="产品介绍：" >
                            <div ref="editor" style="width:90%;"></div>
                        </el-form-item>
                    </el-col>
                </el-row>
            <!-- </el-form> -->
        </div>
        <div class="container" style="margin-top:20px;">
            <h3>关联产品</h3>
            <!-- <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="100px" class="demo-ruleForm"> -->
            <el-form-item
                style="margin-top:20px;"
                required
                v-for="(item, index) in ruleForm.materialProducts"
                :label="'产品' + (index+1)"
                :key="item.key"
                :prop="'materialProducts.' + index + '.materialType'"
                :rules="{
                    required: true, message: '不能为空', trigger: 'change'
                }"
            >
                <el-select v-model="item.materialType" filterable value-key="name" @change="changePin(index)" placeholder="物料类型" style="width:200px">
                    <el-option
                        v-for="item1 in materialType"
                        :key="item1.name"
                        :label="item1.name"
                        :value="item1.name"
                    >
                    {{item1.name}}
                    </el-option>
                </el-select>
                <el-select v-model="item.breedName" filterable  :disabled="item.isDisabled" value-key="id"  placeholder="品名" @change="changeInBatch(item,index)" style="width:200px;margin: 0 15px">
                    <el-option
                        v-for="item2 in trades"
                        :key="item2.breedName"
                        :label="item2.breedName"
                        :value="item2.breedName"
                    >
                    {{item2.breedName}}
                    </el-option>
                </el-select>
                <el-select v-model="item.materialCode" v-if="item.materialType == '配方颗粒'"  filterable value-key="id" :disabled="item.isDisabled" :placeholder="item.placeholder" @change="changeInBatch2(item,index)" style="width:200px;margin: 0 15px">
                    <el-option
                        v-for="item3 in materialCodes"
                        :key="item3.id"
                        :label="item3.inventoryCode"
                        :value="item3"
                    >
                    {{item3.inventoryCode}}
                    </el-option>
                </el-select> 
                <el-select v-model="item.materialCode" v-else filterable value-key="id" :disabled="item.isDisabled" :placeholder="item.placeholder" @change="changeInBatch2(item,index)" style="width:200px;margin: 0 15px">
                    <el-option
                        v-for="item3 in materialCodes"
                        :key="item3.id"
                        :label="item3.materialCode"
                        :value="item3"
                    >
                    {{item3.materialCode}}
                    </el-option>
                </el-select> 
                
                 <el-button style="margin-left:10px" @click.prevent="removeDomain(item)">删除</el-button>
            </el-form-item>
            <el-form-item>
                <el-button @click="addDomain">添加一条</el-button>
            </el-form-item>
            <el-form-item class="footerFixed" style="z-index:9999;">
                    <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                    <el-button @click="backPage">返回</el-button>
                </el-form-item>
        </div>
        </el-form>
    </div>
    
</template>

<script>
    import {product_findmater,product_findbreed,product_save,product_findById,product_update,pack_findPackBreedName,pack_findMaterialBreedMsg} from "@/request/api"
    import uploadImg from '../../../common/uploadImg';
    import E from 'wangeditor';
    export default {
        components: {
            uploadImg
        },
        data() {
            return {
                
                listUrl:'',
                options:[],
                password:'',
                id:'',
                label:'',
                materialCodes:[],
                trades:[],
                materialType:[
                    {name:'中药材'},
                    {name:'辅料'},
                    {name:'提取饮片'},
                    {name:'配方颗粒'},
                ],
                labelPosition:'right',
                allMessage: '',
                ruleForm: {
                    img:'',
                    oldImg:'',
                    price:'',
                    introduce:'',
                    title:'',
                    materialProducts:[{
                        materialBreedId:'',
                        materialType:'',
                        breedName:'',
                        materialCode:''
                    }]
                },
                idList:[],
                rules:{
                    name: [
                        { required: true, message: '不能为空', trigger: 'change' }
                    ],
                },
            };
        },
        
        mounted(){  
             this.id = this.$route.query.id
            if(this.id == undefined){

            }else{
                this.init()
            }
 
            var editor = new E(this.$refs.editor)
            editor.customConfig.uploadImgServer = this.$store.state.uploadImgurl +'/file/upload';
            editor.customConfig.uploadFileName = 'file';
            editor.customConfig.uploadImgHooks = {
                customInsert: function (insertImg, result, editor) {
                    var url =  "http://" + window.location.host + "/file/show/" +  result.data
                    insertImg(url)

                }
            }
	        editor.customConfig.onchange = (html) => {
                this.ruleForm.introduce = html
            }
	        editor.create();
            editor.txt.html(this.ruleForm.introduce)

           
        },
        methods: {
            removeDomain(item){
                if (this.ruleForm.materialProducts.length > 1) {
                    this.$confirm('此操作将删除该条数据, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        var index = this.ruleForm.materialProducts.indexOf(item)
                        if (index !== -1) {
                            this.ruleForm.materialProducts.splice(index, 1)
                        }
                        this.$notify({
                            title: '操作成功',
                            message: '删除成功',
                            type: 'success'
                        });
                    });
                }
            },
            changeInBatch2(item,index){

                this.ruleForm.materialProducts[index].materialBreedId = item.materialCode.id
                if(item.materialType == "配方颗粒"){
                    this.ruleForm.materialProducts[index].materialCode = item.materialCode.inventoryCode
                }else{
                    this.ruleForm.materialProducts[index].materialCode = item.materialCode.materialCode
                }
                // this.ruleForm.materialProducts[index].materialBreedId = item.materialCode.id
                // this.ruleForm.materialProducts[index].materialCode = item.materialCode.materialCode
                
            },
            changeInBatch(item,index){

                let data = {
                    materialType: item.materialType,
                    breedName: item.breedName
                }
                pack_findMaterialBreedMsg(data).then((res)=>{
                    this.materialCodes = res.data
                })
                this.ruleForm.materialProducts[index].breedName = item.breedName
            },
            addDomain(){
                this.ruleForm.materialProducts.push({
                    materialBreedId:'',
                    materialType:'',
                    breedName:'',
                    materialCode:''
                })
            },
            init(){
               product_findById(this.id).then((res)=>{
                   this.ruleForm = res.data
                   var editor = new E(this.$refs.editor)
                   this.ruleForm.oldImg = res.data.img
                    const arr = this.ruleForm.img.split(";")
                    if(arr == ""){

                    }else{
                        this.listUrl = arr.map(t =>{
                            var obj = {}
                            obj.url =this.$store.state.imageUrls + t
                            obj.name = this.$store.state.imageUrls + t
                            return obj
                        })
                    }
                   if(this.ruleForm.materialProducts == null ){
                    //    console.log(1)
                        this.ruleForm.materialProducts =[{
                            materialBreedId:'',
                            materialType:'',
                            breedName:'',
                            materialCode:''
                        }]
                        console.log(this.ruleForm)
                   }else{
                       this.ruleForm.materialProducts = res.data.materialProducts
                   }

                //    var _this =this 
                    editor.customConfig.uploadImgServer = this.$store.state.uploadImgurl +'/file/upload';
                    editor.customConfig.uploadFileName = 'file';
                    editor.customConfig.uploadImgHooks = {
                        customInsert: function (insertImg, result, editor) {
                            var url = "http://" + window.location.host + "/file/show/" +  result.data
                            insertImg(url)
                        }
                    }
                    editor.customConfig.onchange = (html) => {
                        this.ruleForm.introduce = html
                    }
                    editor.create();
                    editor.txt.html(this.ruleForm.introduce)
               })
            },
            changePin(index){
                pack_findPackBreedName({
                    materialType: this.ruleForm.materialProducts[index].materialType
                }).then((res)=>{
                    this.trades = res.data
                })
                // this.ruleForm.materialProducts[index].breedName = ""
                // this.ruleForm.materialProducts[index].materialCode = ""

                if(this.ruleForm.materialProducts[index].materialType == "配方颗粒"){
                    this.ruleForm.materialProducts[index].placeholder = "存货代码"
                }else{
                    this.ruleForm.materialProducts[index].placeholder = "物料代码"
                }
            },
            handleChange(value) {
                
            },
            backPage () {
                this.$router.go(-1);
                
            },
            submitForm(formName) {
                 this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.ruleForm.materialProduct = this.ruleForm.materialProducts
                        const list = JSON.stringify(this.ruleForm.materialProducts)
                        this.ruleForm.materialProduct = list.toString();
                        this.ruleForm.materialProducts = ""
                        // var imgurls = this.$refs.uploadChang.fileList
                        let formdata = new FormData()
                        // var arr=""
                        // for(var i=0;i<imgurls.length;i++){
                        //     if(imgurls[i].status != "success"){
                        //         formdata.append("files",imgurls[i].raw)
                        //     }
                        //     arr += imgurls[i].name + ';'
                        // }
                        // var str = arr.substr(0,arr.length-1)
                        // this.ruleForm.img = str.substring(str.lastIndexOf("/")+1)

                        for(var a in this.ruleForm){
                            if(this.ruleForm[a] == null || this.ruleForm[a] == "null"){
                                this.ruleForm[a] = ""
                                formdata.append(a,'') 
                            }else{
                                formdata.append(a,this.ruleForm[a])
                            }
                        }
                        if(this.id == undefined){
                           product_save(formdata).then((res)=>{
                            this.$notify({
                                    title: '提示',
                                    message: '保存成功',
                                    type: 'success',
                                    duration:1000
                                });
                                this.$router.go(-1)
                            })
                        }else{
                            product_update(formdata).then((res)=>{
                                this.$notify({
                                    title: '提示',
                                    message: '修改成功',
                                    type: 'success'
                                });
                                this.$router.go(-1)
                            })
                        }
                    }else{
                        return false
                    }
                })
            }     
        }
    }
</script>

<style scoped lang="less">
.demo-ruleForm{
    margin-top: 10px;
}
.demo-ruleForm .el-radio--small.is-bordered{
    width: 120px !important;
    margin-right: 10px !important;
}
.box{
    width: 85%;
    margin-bottom: 15px;
    dl{
        margin-bottom: 20px;
        overflow: hidden;
        dt{ margin-bottom: 5px; font-size: 14px;}
        dd{ font-weight: 500; font-size: 12px; float: left; width: 50%; line-height: 24px;}
    }
    dl:last-child{
        margin-bottom: 0;
    }
    .el-col-11{
        height: 200px;
        overflow-y: auto;
        margin-left: 10px;
        border-left: 1px solid #EBEEF5;
        padding-left: 10px;
        p{ color: #303133;}
        .record-tip-con{
            padding-top: 10px;
        }
    }
}
</style>